package org.lsy.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.lsy.dao.AuthCodeRepository;
import org.lsy.pojo.AuthCode;
import org.lsy.service.CodeService;
import org.lsy.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Random;

/**
 * @author SHIYUAN
 * @version 1.0
 */
@Component
@Service
@Slf4j
public class CodeServiceImpl implements CodeService {

    private static final String DEFAULT_SUBJECT = "验证码";

    @Autowired
    private AuthCodeRepository authCodeRepository;

    @Reference
    private MailService mailService;

    @Override
    public boolean createCode(String email) {
        boolean result = false;
        String code = codeGenerator();
        AuthCode authCode = authCodeBuilder(email, code);
        //保存实体类
        try {
            authCodeRepository.save(authCode);
        } catch (Exception e) {
            log.error("保存AuthCode失败，原因:{}", e.toString());
            return false;
        }
        //调用email方法发送验证码
        try {
            mailService.sendSimpleMail(email, DEFAULT_SUBJECT, code);
            result = true;
        } catch (Exception e) {
            log.error("发送email失败，原因:{}", e.toString());
        }
        //如果发送email出现问题,手动回滚
        if (!result) {
            try {
                authCodeRepository.delete(authCode);
            } catch (Exception e) {
                log.error("手动回滚失败，原因:{}", e.toString());
            }
        }
        return result;
    }

    @Override
    public int validateCode(String email, String code) {
        AuthCode authCode = authCodeRepository.findFirstByCodeAndAndEmailOrderByExpiretimeDesc(code, email);
        if (authCode == null) {
            return 1;
        } else if (authCode.getExpiretime().after(new Date())) {
            return 0;
        } else {
            return 2;
        }
    }

    /**
     * 验证码实体类生成器
     * @param email 电子邮件
     * @param code 验证码
     * @return 验证码实体类
     */
    private AuthCode authCodeBuilder(String email, String code) {
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        long currentTimeMillis = System.currentTimeMillis();
        authCode.setCreatetime(new Date(currentTimeMillis));
        authCode.setExpiretime(new Date(currentTimeMillis + 10 * 60 * 1000));
        return authCode;
    }

    /**
     * 生成6位随机数
     * @return 6位随机数
     */
    private String codeGenerator() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
}
